# coding:utf-8
import pymysql
from flask import render_template, redirect, url_for, flash
from flask_login import login_user, logout_user, login_required
from werkzeug.security import check_password_hash

import config
from app.auth import auth
from app.auth.forms import LoginForm
from app.models import User
from app.dbfunc.connect_db import get_conn


@auth.route('/login', methods=['POST', 'GET'])
def login():
    form = LoginForm()
    if form.validate_on_submit():
        if form.name.data == config.ADMIN_USER and form.password.data == config.ADMIN_PASSWORD:
            user = User.query.filter_by(name='admin').first()  # User模型用于用户登入
            login_user(user, form.remember_me)
            return redirect(url_for('main.home2'))
        else:
            # conn = pymysql.connect(
            #     host='127.0.0.1',
            #     user='root',
            #     password='123456',
            #     db='mytest',
            #     charset='utf8')
            conn = get_conn()

            cur = conn.cursor(cursor=pymysql.cursors.DictCursor)
            num = cur.execute('select password from student where name="%s"' % form.name.data)
            psd_hash = cur.fetchone()  # fetchont()返回字典类型，key为字段名，value为字段值
            if num and check_password_hash(psd_hash['password'],
                                           form.password.data):  # 登录条件仍然依赖mysql数据，check_password_hash()验证密码
                user = User.query.filter_by(name=form.name.data).first()  # User模型用于用户登入
                login_user(user, form.remember_me)
                return redirect(url_for('main.home'))
        flash(u'用户名或密码无效！')

        cur.close()
        conn.commit()
        conn.close()
    return render_template('auth/login.html', form=form)

@auth.route('/sigin', methods=['POST', 'GET'])
def sigin():
    form = LoginForm()
    return render_template('auth/login.html', form=form)


@auth.route('/logout')
@login_required
def logout():
    logout_user()
    flash(u'logout！')
    return redirect(url_for('main.home'))
